package dynamic.thread.pool.test.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

@Slf4j
@Configuration
public class ThreadPoolConfig {
    @Bean("testThreadPool")
    public ThreadPoolExecutor testThreadPool() {
        // 核心线程数
        int corePoolSize = 10;
        // 最大线程数
        int maximumPoolSize = 20;
        // 线程空闲时间
        long keepAliveTime = 3L;
        // 时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        // 最大队列数
        int blockQueueSize = 200;

        // 任务队列
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(blockQueueSize);
        // 线程工厂
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("testPool-guava-%d").build();
        // 拒绝策略
        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();

        // 创建线程池
        return new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
    }

    @Bean("commonThreadPool")
    public ThreadPoolExecutor commonThreadPool() {
        // 核心线程数
        int corePoolSize = 20;
        // 最大线程数
        int maximumPoolSize = 50;
        // 线程空闲时间
        long keepAliveTime = 3L;
        // 时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        // 最大队列数
        int blockQueueSize = 500;

        // 任务队列
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(blockQueueSize);
        // 线程工厂
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("commonPool-guava-%d").build();
        // 拒绝策略
        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();

        // 创建线程池
        return new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
    }

    @Bean("taskThreadPool")
    public ThreadPoolTaskExecutor taskThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(30);//核心池大小
        executor.setMaxPoolSize(60);//最大线程数
        executor.setQueueCapacity(500);//队列长度
        executor.setKeepAliveSeconds(10);//线程空闲时间
        executor.setThreadNamePrefix("taskPool-thread-");//线程前缀名称
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());//配置拒绝策略
        executor.initialize();//初始化
        return executor;
    }
}
